<template>
  <s-layout title="会员充值" class="recharge-wrap" navbar="inner">
    <view class="container">
      <view class="header-section">
        <view class="brand-logo">
          <text class="logo-text">巴蜀客家</text>
          <view class="logo-decoration"></view>
        </view>
        <view class="header-title">会员充值</view>
        <view class="header-desc">根据您的会员等级享受专属充值服务</view>
      </view>

      <view class="main-card">
        <view class="current-member-info" v-if="memberData && memberData.currentLevel">
          <view class="section-header">
            <view class="section-icon">👑</view>
            <text class="section-title">当前会员等级</text>
          </view>
          <view class="member-card current">
            <view class="member-badge">
              <view class="badge-icon">{{ getBadgeIcon(memberData.currentLevel.level) }}</view>
              <view class="badge-content">
                <view class="member-title">{{ memberData.currentLevel.title || '会员' }}</view>
                <view class="member-level">等级 {{ memberData.currentLevel.level }}</view>
              </view>
            </view>
            <view class="member-desc" v-if="memberData.currentLevel.levelDesc">
              {{ memberData.currentLevel.levelDesc }}
            </view>
            <view class="member-desc no-desc" v-else>
              暂无等级描述
            </view>
            <view class="member-benefits">
              <view class="benefit-item">
                <text class="benefit-label">充值返点比例：</text>
                <text class="benefit-value">{{ memberData.currentLevel.rebate || '0' }}%</text>
              </view>
              <view class="benefit-item">
                <text class="benefit-label">消费返点比例：</text>
                <text class="benefit-value">{{ memberData.currentLevel.ratio || '0' }}%</text>
              </view>
            </view>
          </view>
        </view>

        <view class="next-member-info" v-if="memberData && memberData.nextLevel">
          <view class="section-header">
            <view class="section-icon">🚀</view>
            <text class="section-title">下一级会员</text>
          </view>
          <view class="member-card next">
            <view class="member-badge">
              <view class="badge-icon">{{ getBadgeIcon(memberData.nextLevel.level) }}</view>
              <view class="badge-content">
                <view class="member-title">{{ memberData.nextLevel.title || '会员' }}</view>
                <view class="member-level">等级 {{ memberData.nextLevel.level }}</view>
              </view>
            </view>
            <view class="member-desc" v-if="memberData.nextLevel.levelDesc">
              {{ memberData.nextLevel.levelDesc }}
            </view>
            <view class="member-benefits">
              <view class="benefit-item">
                <text class="benefit-label">返点比例：</text>
                <text class="benefit-value highlight">{{ memberData.nextLevel.rebate || '0' }}%</text>
              </view>
              <view class="benefit-item">
                <text class="benefit-label">价格比例：</text>
                <text class="benefit-value highlight">{{ memberData.nextLevel.ratio || '0' }}%</text>
              </view>
            </view>
            
            <view class="upgrade-info">
              <view class="upgrade-amount">
                <text class="upgrade-label">升级所需充值：</text>
                <text class="upgrade-value">¥{{ memberData.nextLevel.amount || '0.00' }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="max-level-info" v-if="memberData && !memberData.nextLevel">
          <view class="max-level-card">
            <view class="max-level-icon">🏆</view>
            <view class="max-level-content">
              <view class="max-level-title">恭喜您！</view>
              <view class="max-level-desc">您已经是我们的最高级会员，享受所有专属权益！</view>
              <view class="max-level-thanks">感谢您对巴蜀客家的支持与信任</view>
            </view>
          </view>
        </view>

        <view class="loading-info" v-if="state.loadingLevel">
          <view class="loading-text">正在获取会员等级信息...</view>
        </view>

        <view class="error-info" v-if="!state.loadingLevel && !memberData">
          <view class="error-text">获取会员等级失败，请重试</view>
          <button class="retry-btn" @tap="getMemberLevel">重新获取</button>
        </view>

        <view class="recharge-status" v-if="memberData && memberData.currentLevel">
          <view class="status-card" :class="canRecharge ? 'can-recharge' : 'cannot-recharge'">
            <view class="status-icon">
              <text v-if="canRecharge">✅</text>
              <text v-else>❌</text>
            </view>
            <view class="status-content">
              <view class="status-title">
                {{ canRecharge ? '可以充值升级' : '暂不支持充值' }}
              </view>
              <view class="status-desc">
                {{ getRechargeStatusDesc() }}
              </view>
            </view>
          </view>
        </view>

        <view class="amount-section" v-if="memberData && memberData.nextLevel && canRecharge">
          <view class="amount-box">
            <view class="amount-icon">💰</view>
            <view class="amount-content">
              <view class="amount-label">充值金额</view>
              <view class="amount-value">
                ¥{{ memberData.nextLevel.amount || '0.00' }}
              </view>
            </view>
          </view>
        </view>

        <view class="status-section" v-if="state.status">
          <view class="status-box" :class="state.statusClass">
            <view class="status-icon">
              <text v-if="state.statusClass === 'status-loading'">⏳</text>
              <text v-else-if="state.statusClass === 'status-success'">✅</text>
              <text v-else-if="state.statusClass === 'status-error'">❌</text>
            </view>
            <view class="status-text">{{ state.statusText }}</view>
          </view>
        </view>

        <view class="button-section" v-if="memberData">
          <button
            class="recharge-btn"
            @tap="onRecharge"
            :disabled="!canRecharge || state.loading"
          >
            <view class="btn-content">
              <text class="btn-icon">{{ state.loading ? '⏳' : getButtonIcon() }}</text>
              <text class="btn-text">{{ getButtonText() }}</text>
            </view>
          </button>
        </view>
      </view>

      <view class="decoration-elements">
        <view class="bamboo-left"></view>
        <view class="bamboo-right"></view>
        <view class="cloud-decoration cloud1"></view>
        <view class="cloud-decoration cloud2"></view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import sheep from '@/sheep';

  const memberData = ref(null);

  const state = reactive({
    loading: false,
    loadingLevel: true,
    status: false,
    statusText: '',
    statusClass: ''
  });

  const canRecharge = computed(() => {
    return memberData.value && 
           memberData.value.currentLevel && 
           memberData.value.currentLevel.recharged === 1 &&
           memberData.value.nextLevel && 
           memberData.value.nextLevel.amount > 0;
  });

  function getBadgeIcon(level) {
    const icons = ['🥉', '🥈', '🥇', '💎', '👑', '🏆'];
    return icons[level] || '🎖️';
  }

  function getRechargeStatusDesc() {
    if (!memberData.value || !memberData.value.currentLevel) {
      return '获取会员信息中...';
    }

    if (!memberData.value.nextLevel) {
      return '您已是最高级会员，无需充值升级';
    }

    if (memberData.value.currentLevel.recharged !== 1) {
      return '当前条件暂不支持充值升级';
    }

    return `充值 ¥${memberData.value.nextLevel.amount} 即可升级到 ${memberData.value.nextLevel.title}`;
  }

  function getButtonIcon() {
    if (!canRecharge.value) {
      return '🚫';
    }
    return '💳';
  }

  function getButtonText() {
    if (state.loading) {
      return '处理中...';
    }

    if (!memberData.value) {
      return '获取信息中...';
    }

    if (!memberData.value.nextLevel) {
      return '已是最高级会员';
    }

    if (memberData.value.currentLevel && memberData.value.currentLevel.recharged !== 1) {
      return '当前条件不支持充值';
    }

    if (!canRecharge.value) {
      return '无法充值';
    }

    return `立即充值升级到 ${memberData.value.nextLevel.title}`;
  }

  async function getMemberLevel() {
    state.loadingLevel = true;
    try {
      const result = await sheep.$api.user.memberLevel();

      if (result && result.currentLevel) {
        memberData.value = result;
      } else {
        uni.showToast({
          title: '获取会员等级失败',
          icon: 'error'
        });
      }
    } catch (error) {
      uni.showToast({
        title: '获取会员等级失败',
        icon: 'error'
      });
    } finally {
      state.loadingLevel = false;
    }
  }

  async function onRecharge() {
    if (!canRecharge.value || state.loading) {
      let message = '无法充值';
      
      if (!memberData.value) {
        message = '会员信息获取失败';
      } else if (!memberData.value.nextLevel) {
        message = '您已是最高级会员';
      } else if (memberData.value.currentLevel && memberData.value.currentLevel.recharged !== 1) {
        message = '当前条件不支持充值升级';
      } else if (!memberData.value.nextLevel.amount || memberData.value.nextLevel.amount <= 0) {
        message = '升级金额无效';
      }

      uni.showToast({
        title: message,
        icon: 'none'
      });
      return;
    }

    state.loading = true;
    state.status = true;
    state.statusText = '正在获取预支付信息...';
    state.statusClass = 'status-loading';

    try {
      const result = await sheep.$api.pay.wechatRecharge();

      if (result && result.appId && result.timeStamp && result.paySign) {
        
        setTimeout(() => {
          uni.requestPayment({
            provider: "wxpay",
            appId: result.appId,
            timeStamp: result.timeStamp,
            nonceStr: result.nonceStr,
            package: result.packageValue,
            signType: result.signType,
            paySign: result.paySign,
            success: function(res) {
              state.statusText = '支付成功，正在更新会员等级...';
              state.statusClass = 'status-success';
              
              setTimeout(() => {
                getMemberLevel();
                state.status = false;
              }, 2000);
            },
            fail: function(err) {
              if (err.errMsg && err.errMsg.includes('cancel')) {
                state.statusText = '支付已取消';
              } else {
                state.statusText = '支付失败，请重试';
              }
              state.statusClass = 'status-error';
              
              setTimeout(() => {
                state.status = false;
              }, 3000);
            },
          });
        }, 1000);

      } else {
        state.statusText = '获取支付信息失败，请重试';
        state.statusClass = 'status-error';
      }
    } catch (error) {
      state.statusText = '网络请求失败，请检查网络连接或稍后重试';
      state.statusClass = 'status-error';
    } finally {
      state.loading = false;
    }
  }

  onMounted(() => {
    getMemberLevel();
  });
</script>

<style lang="scss" scoped>
$primary-color: #8b4513;
$secondary-color: #daa520;
$accent-color: #228b22;
$text-dark: #333;
$text-light: #666;
$bg-light: #fff8dc;
$success-color: #27ae60;
$warning-color: #f39c12;
$error-color: #e74c3c;

.recharge-wrap {
  background: linear-gradient(135deg, $primary-color 0%, #a0522d 100%);
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

.container {
  position: relative;
  z-index: 2;
  padding: 40rpx;
  min-height: 100vh;
}

.header-section {
  text-align: center;
  margin-bottom: 60rpx;
  padding-top: 40rpx;

  .brand-logo {
    margin-bottom: 30rpx;

    .logo-text {
      font-size: 48rpx;
      font-weight: bold;
      color: #9f512b;
      font-family: "楷体", "KaiTi", serif;
      text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
    }

    .logo-decoration {
      width: 100rpx;
      height: 4rpx;
      background: linear-gradient(
        90deg,
        transparent,
        $secondary-color,
        transparent
      );
      margin: 15rpx auto 0;
      border-radius: 2rpx;
    }
  }

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #9f512b;
    margin-bottom: 15rpx;
    font-family: "楷体", "KaiTi", serif;
  }

  .header-desc {
    font-size: 26rpx;
    color: #9f512b;
    letter-spacing: 2rpx;
    opacity: 0.8;
  }
}

.main-card {
  background: white;
  border-radius: 30rpx;
  padding: 50rpx 40rpx;
  box-shadow: 0 30rpx 60rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  border: 2rpx solid rgba($secondary-color, 0.3);
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 8rpx;
    background: linear-gradient(90deg, $secondary-color 0%, #f4a460 100%);
  }
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;

  .section-icon {
    font-size: 36rpx;
    margin-right: 15rpx;
  }

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: $primary-color;
    font-family: "楷体", "KaiTi", serif;
  }
}

.current-member-info,
.next-member-info {
  margin-bottom: 40rpx;
}

.member-card {
  padding: 30rpx;
  border-radius: 20rpx;
  border: 2rpx solid;

  &.current {
    background: linear-gradient(135deg, rgba($primary-color, 0.05) 0%, rgba($primary-color, 0.1) 100%);
    border-color: rgba($primary-color, 0.2);
  }

  &.next {
    background: linear-gradient(135deg, rgba($secondary-color, 0.05) 0%, rgba($secondary-color, 0.1) 100%);
    border-color: rgba($secondary-color, 0.3);
  }

  .member-badge {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .badge-icon {
      font-size: 48rpx;
      margin-right: 20rpx;
    }

    .badge-content {
      flex: 1;

      .member-title {
        font-size: 32rpx;
        font-weight: bold;
        color: $primary-color;
        margin-bottom: 8rpx;
        font-family: "楷体", "KaiTi", serif;
      }

      .member-level {
        font-size: 24rpx;
        color: $text-light;
      }
    }
  }

  .member-desc {
    font-size: 26rpx;
    color: $text-dark;
    line-height: 1.6;
    margin-bottom: 20rpx;
    white-space: pre-wrap;

    &.no-desc {
      color: $text-light;
      font-style: italic;
    }
  }

  .member-benefits {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;

    .benefit-item {
      display: flex;
      align-items: center;

      .benefit-label {
        font-size: 24rpx;
        color: $text-light;
      }

      .benefit-value {
        font-size: 26rpx;
        font-weight: bold;
        color: $primary-color;
        margin-left: 8rpx;

        &.highlight {
          color: $secondary-color;
        }
      }
    }
  }

  .upgrade-info {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx dashed rgba($secondary-color, 0.3);

    .upgrade-amount {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .upgrade-label {
        font-size: 28rpx;
        color: $text-dark;
        font-weight: 500;
      }

      .upgrade-value {
        font-size: 32rpx;
        font-weight: bold;
        color: $secondary-color;
      }
    }
  }
}

.max-level-info {
  margin-bottom: 40rpx;

  .max-level-card {
    padding: 40rpx;
    background: linear-gradient(135deg, rgba($success-color, 0.05) 0%, rgba($success-color, 0.1) 100%);
    border: 2rpx solid rgba($success-color, 0.3);
    border-radius: 20rpx;
    text-align: center;

    .max-level-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
    }

    .max-level-content {
      .max-level-title {
        font-size: 36rpx;
        font-weight: bold;
        color: $success-color;
        margin-bottom: 15rpx;
        font-family: "楷体", "KaiTi", serif;
      }

      .max-level-desc {
        font-size: 28rpx;
        color: $text-dark;
        margin-bottom: 15rpx;
        line-height: 1.6;
      }

      .max-level-thanks {
        font-size: 24rpx;
        color: $text-light;
        font-style: italic;
      }
    }
  }
}

.recharge-status {
  margin-bottom: 30rpx;

  .status-card {
    display: flex;
    align-items: center;
    padding: 25rpx;
    border-radius: 15rpx;
    border: 2rpx solid;

    &.can-recharge {
      background: rgba($success-color, 0.1);
      border-color: rgba($success-color, 0.3);

      .status-title {
        color: $success-color;
      }
    }

    &.cannot-recharge {
      background: rgba($warning-color, 0.1);
      border-color: rgba($warning-color, 0.3);

      .status-title {
        color: $warning-color;
      }
    }

    .status-icon {
      font-size: 32rpx;
      margin-right: 20rpx;
    }

    .status-content {
      flex: 1;

      .status-title {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }

      .status-desc {
        font-size: 24rpx;
        color: $text-light;
        line-height: 1.4;
      }
    }
  }
}

.loading-info,
.error-info {
  margin-bottom: 40rpx;
  padding: 30rpx;
  text-align: center;
  border-radius: 20rpx;
}

.loading-info {
  background: rgba($warning-color, 0.1);
  border: 2rpx solid rgba($warning-color, 0.3);

  .loading-text {
    color: $warning-color;
    font-size: 28rpx;
  }
}

.error-info {
  background: rgba($error-color, 0.1);
  border: 2rpx solid rgba($error-color, 0.3);

  .error-text {
    color: $error-color;
    font-size: 28rpx;
    margin-bottom: 20rpx;
  }

  .retry-btn {
    background: $error-color;
    color: white;
    border: none;
    border-radius: 10rpx;
    padding: 10rpx 30rpx;
    font-size: 26rpx;
  }
}

.amount-section {
  margin-bottom: 40rpx;

  .amount-box {
    display: flex;
    align-items: center;
    background: linear-gradient(135deg, $bg-light 0%, #f5f5dc 100%);
    border-radius: 20rpx;
    padding: 40rpx;
    border: 2rpx solid rgba($secondary-color, 0.2);

    .amount-icon {
      font-size: 60rpx;
      margin-right: 30rpx;
    }

    .amount-content {
      flex: 1;

      .amount-label {
        font-size: 28rpx;
        color: $text-light;
        margin-bottom: 10rpx;
        font-family: "楷体", "KaiTi", serif;
      }

      .amount-value {
        font-size: 56rpx;
        font-weight: bold;
        color: $primary-color;
        font-family: "OPPOSANS", monospace;
        text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.status-section {
  margin-bottom: 40rpx;

  .status-box {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-radius: 16rpx;
    border: 2rpx solid;

    .status-icon {
      font-size: 32rpx;
      margin-right: 20rpx;
    }

    .status-text {
      flex: 1;
      font-size: 28rpx;
      font-weight: 500;
      line-height: 1.6;
    }

    &.status-loading {
      background: rgba($warning-color, 0.1);
      border-color: rgba($warning-color, 0.3);
      color: $warning-color;
    }

    &.status-success {
      background: rgba($success-color, 0.1);
      border-color: rgba($success-color, 0.3);
      color: $success-color;
    }

    &.status-error {
      background: rgba($error-color, 0.1);
      border-color: rgba($error-color, 0.3);
      color: $error-color;
    }
  }
}

.button-section {
  margin-bottom: 30rpx;

  .recharge-btn {
    width: 100%;
    height: 96rpx;
    background: linear-gradient(135deg, $primary-color 0%, #a0522d 100%);
    border: none;
    border-radius: 48rpx;
    box-shadow: 0 12rpx 32rpx rgba($primary-color, 0.4);
    position: relative;
    overflow: hidden;

    &:active {
      transform: translateY(2rpx);
    }

    &:disabled {
      opacity: 0.6;
      transform: none;
      background: #ccc;
      box-shadow: none;
    }

    .btn-content {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      .btn-icon {
        font-size: 32rpx;
        margin-right: 15rpx;
      }

      .btn-text {
        font-size: 28rpx;
        font-weight: bold;
        color: white;
        font-family: "楷体", "KaiTi", serif;
        letter-spacing: 2rpx;
        text-align: center;
      }
    }
  }
}

.decoration-elements {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 1;

  .bamboo-left,
  .bamboo-right {
    position: absolute;
    width: 60rpx;
    height: 250rpx;
    background: linear-gradient(
      to bottom,
      rgba($accent-color, 0.1) 0%,
      rgba(darken($accent-color, 10%), 0.15) 50%,
      rgba($accent-color, 0.1) 100%
    );
    border-radius: 30rpx;
  }

  .bamboo-left {
    left: 20rpx;
    top: 200rpx;
    transform: rotate(-10deg);
  }

  .bamboo-right {
    right: 20rpx;
    top: 150rpx;
    transform: rotate(10deg);
  }

  .cloud-decoration {
    position: absolute;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50rpx;

    &.cloud1 {
      width: 120rpx;
      height: 50rpx;
      top: 15%;
      left: 8%;
    }

    &.cloud2 {
      width: 100rpx;
      height: 40rpx;
      top: 70%;
      right: 10%;
    }
  }
}

@media screen and (max-width: 750rpx) {
  .container {
    padding: 30rpx 20rpx;
  }

  .header-section {
    margin-bottom: 40rpx;

    .brand-logo .logo-text {
      font-size: 40rpx;
    }

    .header-title {
      font-size: 32rpx;
    }
  }

  .main-card {
    padding: 40rpx 30rpx;
  }
}
</style>
